<?php
namespace app\home\common;
/**
 * Created by PhpStorm.
 * User: YD
 * Date: 2017/4/25
 * Time: 15:45
 */
use app\infrastructure\uri\Uri;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use think\Request;
class Common  extends \think\Controller
{
    public $auth;
    /**
     * @var 七牛上传密钥
     */
    public $akey = 'opwxCQPEiE0lgG64ICmmzgS_opIFsgmEnYp_lVdq';
    public $skey = 'yUrwkmNKoRfa8XNoQ9hTmCjpuuq6aYPe8L5nE3QY';
    /**
     * @var 七牛访问地址
     */
    public $qiniuUrl = 'http://7xj3cg.com2.z0.glb.qiniucdn.com/';
    /**
     *
     * @var 七牛访问https访问地址
     */
    public $qiNiuHost = 'https://dn-etcp.qbox.me/';

    public  function  __construct(){
        parent::__construct();
        if(!session('username')){
            $this->redirect('home/index/index');
        }
        $request = request::instance();
        $module=$request->module();
        $controller=$request->controller();
        $domain=$request->domain();
        $action=$request->action();
        $this->assign('controller',$controller);
        $this->assign('action',$action);
        $this->assign('domain',$domain);
        $path=strtolower($module.'/'.$controller.'/'.$action);
        $this->assign('path',$path);
        //获取该用户的所有权限
        $auth=$this->getauth();
//        $this->auth=$auth;
        //权限判断,菜单级权限
//        if(!in_array($path,$auth)){
//            $this->redirect('home/entry/index');die;
//        }
        $this->assign('auth',$auth);
    }

    private function getauth(){
        $username=session('username');
        $username=substr($username,0,5);
       if($username == 'admin'){
          session('role','admin');
       }elseif($username == 'testi'){
           session('role','testing');
       }
          if(session('userAuth')){
              return session('userAuth');
          }else{
              $id=session('userid');
              $url=Uri::HOST.Uri::FINDADMINUSERAUTH.$id;
              $auth=(new \app\infrastructure\uri\Request())->getArrayData($url);
              $userAuth=[];
              if($auth['code'] == 0){
                  foreach($auth['data'] as $k=>$v){
                      $userAuth[]=strtolower($v['content']);
                  }
                  session('userAuth',$userAuth);
              }
              return $userAuth;
          }
    }

    /**
     * 七牛文件上传，上传任何格式
     */
    public function uploadqiniu(){
          $auth=new Auth($this->akey, $this->skey);
        $bucketMgr= new BucketManager($auth);
        $bucket = 'parkmanage';
        $token = $auth->uploadToken($bucket, null, 3600, null);
        $upload= new UploadManager();
        if ($_FILES['Filedata']['error'] != 0) {
            $result = ['valid' => 0, 'msg' => '上传出错，错误代码:' . $_FILES['Filedata']['error']];
            echo json_encode($result);
            exit;
        }
        //上传的临时文件
        $tempFile = $_FILES['Filedata']['tmp_name'];
        //用户上传的文件信息
        $fileParts = pathinfo($_FILES['Filedata']['name']);
        //检测文件大小
        if($_FILES['Filedata']['size']>(500*1024*1024)){
            $res = ['valid' => 0, 'msg' => '文件大小大于500M'];
            echo json_encode($res);
            die;
        }
        $file = $tempFile;
        $editFile = 'app/' . uniqid() . '.' . $fileParts['extension'];
        list($ret, $err) = $upload->putFile($token, $editFile, $file);
        if ($err !== null) {
            echo json_encode(['valid' => 0, 'msg' => $err]);
            die;
        } else {
            //$this->ajaxReturn('http://7xj3cg.com2.z0.glb.qiniucdn.com/'.$ret['key']);
            $res = ['valid' => 1, 'msg' => 'http://7xj3cg.com2.z0.glb.qiniucdn.com/' . $ret['key'],'fileSize'=>$_FILES['Filedata']['size']];
            echo json_encode($res);
            die;
        }
    }

    /**
     * 上传文件
     */
    public function uploadFile($file,$type='banner'){
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file($file);
        $root="/var/www/html";
        if($type == 'banner'){
            $path='/uploads/assets/image/banner';
        }else{
            $path='/uploads/assets/image/others';
        }
            // 移动到框架应用根目录/public/uploads/ 目录下
            if($file){
                $info = $file->move($root.$path);
                if($info){
                    $url=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$path;
                   return ['valid'=>0,'data'=>$url.'/'.$info->getSaveName()];
                }else{
                    // 上传失败获取错误信息
                    return ['valid'=>1,'data'=>$file->getError()];
                }
            }
        }

    /**
     * 导出到excel
     */
    public function extendToExcel($data){
        $titlename='';
        $title='';
        $filename=date("Y年m月d日H时i分s秒", time()).'.xls';
        $str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>";
        $str .="<table border=1><head>".$titlename."</head>";
        $str .= $title;
        foreach ($data  as $key=> $rt )
        {
            $str .= "<tr>";
            foreach ( $rt as $k => $v )
            {
                $str .= "<td>{$v}</td>";
            }
            $str .= "</tr>\n";
        }
        $str .= "</table></body></html>";
        header( "Content-Type: application/vnd.ms-excel; name='excel'" );
        header( "Content-type: application/octet-stream" );
        header( "Content-Disposition: attachment; filename=".$filename );
        header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
        header( "Pragma: no-cache" );
        header( "Expires: 0" );
        exit( $str );
    }

    /**
     * 导出为csv文件
     */
    public function extendToCsv($data){
        $filename=date("Y年m月d日H时i分s秒", time()).'.csv';
        $str='';
        foreach($data[0] as $k=>$v){
         $str .= $k.",";
        }
        $str=substr($str,0,-1);
        $str=$str."\n";
        foreach ($data  as $key=> $rt )
        {
            foreach ( $rt as $k => $v )
            {
                $v= str_replace(',',"|",$v);
                $v=strval($v);
                $str .= "\t".$v.',';
            }
            $str=substr($str,0,-1);
            $str=$str."\n";
        }
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        exit( $str );
    }

    /**
     * 导出为csv文件
     */
    public function extendToCsvNoTab($data){
        $filename=date("Y年m月d日H时i分s秒", time()).'.csv';
        $str='';
        foreach($data[0] as $k=>$v){
         $str .= $k.",";
        }
        $str=substr($str,0,-1);
        $str=$str."\n";
        foreach ($data  as $key=> $rt )
        {
            foreach ( $rt as $k => $v )
            {
                $v= str_replace(',',"|",$v);
                $v=strval($v);
                $str .= $v.',';
            }
            $str=substr($str,0,-1);
            $str=$str."\n";
        }
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        exit( $str );
    }

    /**
     * 标准时间转成印度时间,sequelize时间
     */
    public function gmtToIndiaTime($time){
       $strTime= strtotime($time);
//        dd($strTime);
//        $strTime= $strTime + 5.5*3600;
//        dd($strTime);
        $strTime=date("Y-m-d H:i:s",$strTime);
        return $strTime;
    }
    /**
     * 直接查库时间转换
     */
    public function gmtToIndiaTimeByMysql($time){
        $strTime= strtotime($time);
//        dd($strTime);
        $strTime= $strTime + 5.5*3600;
//        dd($strTime);
        $strTime=date("Y-m-d H:i:s",$strTime);
        return $strTime;
    }

}